/**
 * 楼盘参数设置
 */
define(function (require, exports, module) {
    var angular = require("angular");
    var ui = require('ui');
    var util = require('util');
    require("plugins/jqtree/jqtree.css");
    require("angular-ui");
    require("service/ng_service/environment");

    angular
        .module('ProjectHousesParam', ['EnvironmentService'])
        .controller('HousesParamController', ['$rootScope', '$scope', '$http', '$location', '$routeParams', 'environment',
            function ($rootScope, $scope, $http, $location, $routeParams, environment) {
                $scope.tabs = [
                    {
                        value: "DealProductType",
                        name: '成交产品类型'
                    },
                    {
                        value: "brokerBld",
                        name: '建筑类型'
                    },
                    {
                        value: "brokerMng",
                        name: '物业类型'
                    },
                    {
                        value: "brokerStatus",
                        name: '楼盘状态'
                    },
                    {
                        value: "brokerLable",
                        name: '楼盘动态标签'
                    }
                ];

                function getTabValue(tabValue) {
                    var tab;
                    for (var i = 0; tab = $scope.tabs[i]; i++) {
                        if (tab.value === tabValue) {
                            return tabValue;
                        }
                    }
                    return $scope.tabSelectedValue || $scope.tabs[0].value;
                }

                function getSelectedTab() {
                    var tabSelectedValue = $scope.tabSelectedValue;
                    var tabs = $scope.tabs;
                    var tab;
                    for (var i = 0; tab = tabs[i]; i++) {
                        if (tab.value === tabSelectedValue) {
                            return tab;
                        }
                    }
                    return null;
                }

                $scope.tabSelectedValue = getTabValue($routeParams.tab) || $scope.tabs[0].value;

                $rootScope.$on('$locationChangeStart', function (e, newUrl, oldUrl) {
                    var urlObj = util.getUrlObj(newUrl);
                    var oldUrlObj = util.getUrlObj(oldUrl);
                    if (util.getUrlObj(urlObj.hash).pathname === util.getUrlObj(oldUrlObj.hash).pathname) {
                        var newTab = util.getUrlPara('tab', urlObj.hash);
                        if (getTabValue(newTab) !== newTab) {
                            e.preventDefault();
                        }
                    }
                });

                $scope.setEnable = function (item) {
                    postData(
                        'enable-cim-data',
                        {
                            id: item.myParamValueId,
                            type: getSelectedTab().value
                        },
                        '设置成功',
                        true
                    )
                };

                $scope.setTabSelected = function (tab) {
                    $scope.tabSelectedValue = tab.value;
                    $location.search('tab', $scope.tabSelectedValue);
                };

                $scope.setDefault = function (item) {
                    postData(
                        'set-cim-default',
                        {
                            id: item.myParamValueId,
                            type: getSelectedTab().value,
                            token: $scope.curProjectId
                        },
                        '设置成功',
                        true,
                        function () {
                            item.IsDefault = '1';
                        });
                };

                $scope.edit = function (item, dialogModel, dialogScope) {
                    postData(
                        'edit-cim-data',
                        {
                            id: item.myParamValueId,
                            text: item.Text,
                            value: item.Value,
                            order: item.Order,
                            desc: item.Description,
                            token: $scope.curProjectId
                        },
                        '新增成功',
                        true,
                        function (res) {
                            if (res.retCode == 0) {
                                dialogModel.close();
                            }
                        }
                    );
                    return false;
                };

                $scope.add = function (item, dialogModel, dialogScope) {
                    postData(
                        'add-cim-data',
                        {
                            id: item.myParamValueId,
                            text: item.Text,
                            value: item.Value,
                            order: item.Order,
                            desc: item.Description,
                            type: getSelectedTab().value,
                            parentCode: $scope.selectedItem ? $scope.selectedItem.Code : '-1',
                            token: $scope.curProjectId
                        },
                        '新增成功',
                        true,
                        function (res) {
                            if (res.retCode == 0) {
                                dialogModel.close();
                            }
                        }
                    );
                    return false;
                };

                $scope.setDisable = function (item) {
                    util.confirm('确定禁用吗？', {
                        ok: function () {
                            postData('disable-cim-data', {
                                id: item.myParamValueId,
                                token: $scope.curProjectId
                            }, '设置成功', true);
                        }
                    })
                };

                $scope.delete = function (item) {
                    var msg = '确定删除吗？';
                    if (item.children && item.children.length > 0) {
                        msg += '(删除时会同步删除子级)';
                    }
                    util.confirm(msg, {
                        ok: function () {
                            postData('del-cim-data', {
                                id: item.myParamValueId,
                                token: $scope.curProjectId
                            }, '删除成功', true);
                        }
                    })
                };

                $scope.moveDown = function (item) {
                    var list = $scope.list;

                    if (item.parent) {
                        list = item.parent.children;
                    }

                    var curPos = util.indexOf(item, list);
                    var curOrder = item.Order;
                    var NextOrder = list[curPos + 1].Order;

                    if (curOrder == NextOrder) {
                        if (curPos < list.length - 1) {
                            list[curPos] = list[curPos + 1];
                            list[curPos + 1] = item;
                            ui.showSucTip('下移成功');
                        }
                    } else {
                        postData(
                            'down-move',
                            {
                                id: item.myParamValueId,
                                type: getSelectedTab().value,
                                proId: $scope.curProjectId
                            },
                            '下移成功',
                            false,
                            function (res) {
                                if (typeof res.data === 'undefined') {
                                    getData();
                                }
                            });
                    }
                };

                $scope.moveUp = function (item) {
                    var list = $scope.list;

                    if (item.parent) {
                        list = item.parent.children;
                    }

                    var curPos = util.indexOf(item, list);
                    var curOrder = item.Order;
                    var preOrder = list[curPos - 1].Order;
                    if (curOrder == preOrder) {
                        if (curPos > 0) {
                            list[curPos] = list[curPos - 1];
                            list[curPos - 1] = item;
                            ui.showSucTip('上移成功');
                        }

                    } else {
                        postData(
                            'up-move',
                            {
                                id: item.myParamValueId,
                                type: getSelectedTab().value,
                                proId: $scope.curProjectId
                            },
                            '上移成功',
                            false,
                            function (res) {
                                if (typeof res.data === 'undefined') {
                                    getData();
                                }
                            });
                    }
                };
                $scope.reset = function () {
                    util.confirm('确定还原备选项吗？', {
                        ok: function () {
                            postData('reduction-option', {
                                type: getSelectedTab().value,
                                token: $scope.curProjectId
                            }, '还原备选项成功', true);
                        }
                    })
                };

                $scope.selectedItem = null;
                $scope.clickItem = function (item, event) {
                    if ($scope.selectedItem === item) {
                        $scope.selectedItem = null;
                    } else {
                        $scope.selectedItem = item;
                    }
                };

                $scope.clickItemCollapse = function (item) {
                    item.open = !item.open;

                    //关闭时，需将子孙级都关闭
                    if (!item.open) {
                        if (item.children) {
                            setItemOpen(item.children, false);
                        }
                    }
                };

                function setItemOpen(list, open) {
                    var item;
                    for (var i = 0; item = list[i]; i++) {
                        item.open = open;
                        if (item.children) {
                            setItemOpen(item.children, open);
                        }
                    }
                }

                /**
                 * @param {string} urlPath
                 * @param {Object} data
                 * @param {string} sucTip
                 * @param {boolean=} updateData
                 * @param {function=} sucCallback
                 */
                function postData(urlPath, data, sucTip, updateData, sucCallback) {
                    $http
                        .post(G_CONFIG.api_prefix + "qmyx/para-setting/" + urlPath, data)
                        .success(function (res) {
                            var retCode = res.retCode;
                            if (retCode == 0) {
                                if (updateData) {
                                    getData();
                                }

                                sucCallback && sucCallback(res);

                                ui.showSucTip(sucTip);
                            } else {
                                ui.showErrTip(res.errMsg);
                            }
                        })
                }

                /**
                 * 是否开发环境
                 * @type {boolean}
                 */
                var isDev = false;

                $scope.showEditPop = function (data, dialog, dialogScope) {
                    dialogScope.isDev = isDev;
                };

                /**
                 * 获取子集
                 * @param {{Code:string,ParentCode:string}} target
                 * @param {Array.<{Code:string,ParentCode:string}>} list
                 * @returns {Array}
                 */
                function getChildren(target, list) {
                    var res = [];
                    var item;
                    for (var i = 0; item = list[i]; i++) {
                        if (target.Code === item.ParentCode) {
                            res.push(item);
                            item.isChild = true;
                            item.parent = target;
                        }
                    }
                    sortByOrder(res);
                    return res;
                }

                /**
                 * @param {Array.<{Order:string}>} list
                 */
                function sortByOrder(list) {
                    list.sort(function (a, b) {
                        return a.Order - b.Order
                    });
                }

                function setLevel(list) {
                    if (list && list.length > 0) {
                        var item;
                        for (var i = 0; item = list[i]; i++) {
                            if (item.parent) {
                                item.level = item.parent.level + 1;
                            } else {
                                item.level = 0;
                            }

                            setLevel(item.children);
                        }
                    }
                }

                $scope.loading = false;
                /**
                 * 获取数据
                 * @param {string=} projectId
                 */
                var getData = function (projectId) {
                    projectId = projectId || $scope.curProjectId;

                    $scope.loading = true;
                    environment()
                        .then(function (res) {
                            isDev = res == 'dev';
                        })
                        .finally(function () {
                            $http
                                .get(G_CONFIG.api_prefix + "qmyx/para-setting/get-building-para-list", {params: {proId: projectId}})
                                .then(function (res) {
                                    var retCode = res.data.retCode;
                                    if (retCode == 0) {
                                        var data = res.data.data;
                                        var list = data[$scope.tabSelectedValue];

                                        for (var i = 0, item; item = list[i]; i++) {
                                            item.Order = parseInt(item.Order);
                                        }

                                        if ('DealProductType' === $scope.tabSelectedValue) {
                                            var item;
                                            for (var i = 0, item; item = list[i]; i++) {
                                                item.open = true;
                                                item.children = getChildren(item, list);
                                            }

                                            //从原始数组中删除是子元素的item
                                            for (var i = 0, item; item = list[i]; i++) {
                                                if (item.isChild) {
                                                    list.splice(i, 1);
                                                    i--;
                                                }
                                            }

                                            setLevel(list);
                                        }

                                        sortByOrder(list);

                                        $scope.data = data;
                                        $scope.list = list;
                                    }
                                })
                                .finally(function () {
                                    $scope.loading = false;
                                })
                        })
                };

                $scope.$watch('curProjectId', function () {
                    var curProjectId = $scope.curProjectId;
                    if (curProjectId) {
                        getData(curProjectId);
                    }
                });
            }])
        .directive("listTpl", ['$compile', function ($compile) {
            return {
                restrict: 'A',
                replace: true,
                link: function ($scope, $element, $attrs) {
                    var content = $compile($('#list_tpl').html())($scope);
                    $element.replaceWith(content);
                }
            };
        }])
});